/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.handlers.meta;

import static cn.ac.iie.di.ban.news.server.handlers.data.DataHandler.getTracer;
import cn.ac.iie.di.ban.news.server.runtime.RuntimeEnv;
import static cn.ac.iie.di.ban.news.server.runtime.RuntimeEnv.getParamAsStrings;
import cn.ac.iie.di.ban.news.server.util.HostInfoKeeper;
import cn.ac.iie.di.ban.news.server.util.HttpUtils;
import cn.ac.iie.di.ban.news.server.util.KeyInfoKeeper;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author zwlin
 */
public class DispatchHandler implements HandlerI {

    private static final Logger logger = Logger.getLogger(DispatchHandler.class);
    private static HostInfoKeeper hostKeeper = null;
    private static KeyInfoKeeper keyKeeper = null;

    public static void init(HostInfoKeeper hostInfoKeeper, KeyInfoKeeper keyInfoKeeper) {
        DispatchHandler.hostKeeper = hostInfoKeeper;
        DispatchHandler.keyKeeper = keyInfoKeeper;
    }

    @Override
    public void init() throws Exception {
        if (hostKeeper == null || keyKeeper == null) {
            throw new Exception("hostKeepr or keyKeeper not set.");
        }
    }

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

//		String ips = "192.168.11.95\n"
//				+ "192.168.11.96\n"
//				+ "192.168.11.97";
//		response.getWriter().print(ips);
            String version = request.getParameter("version");
            if (version == null || version.trim().isEmpty()) {
                version = "J0.1";
            }
            String key = request.getParameter("key");
            if (key == null || key.trim().isEmpty()) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "param key not exist.");
                return;
            }
            logger.info("key: " + key);
//        if (key.contains("91d82e3ef4c88e4aa8cd630a2f2973d0")) {
//            logger.info("wangyi! ! ! " + (keyKeeper.isActivated(key)) + " : " + (keyKeeper.isOnline(key) + " : " + (keyKeeper.isTest(key))));
//        }
            key = key.trim();
            if (keyKeeper.isOnline(key)) {
//            logger.info(key + " is online");
//                String content = request.getParameter("content");
//                JSONObject obj;
//                try {
//                    obj = JSONObject.parseObject(content);
//                } catch (Exception e) {
//                    logger.info("error json: " + content);
//                    logger.error("json parse error. " + ExceptionUtils.getStackTrace(e));
//                if (getTracer() != null) {
//                    getTracer().traceJsonParseError(key, content, recvTimeSec);
//                }
//                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
//                            "3. content cannot be parsed to json.");
//                    return;
//                }
//            logger.info(key + " is online2");
//                if (null == obj) {
//                    logger.info("error json: " + content);
//                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
//                            "3. content cannot be parsed to json.");
//                    return;
//                }
//                String type = obj.getString("msg_type");
//                if (!(keyKeeper.isActivated(key) || keyKeeper.isActivated(key + type))) {
////                logger.info(key + " is online3");
//                    logger.info(key + "key not activated");
//                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
//                            "key not activated for online data load.");
//                    return;
//                }
//            logger.info(key + " is online4");
//            if (key.equals("91d82e3ef4c88e4aa8cd630a2f2973d0")) {
//                logger.info("网易! ! ! " + (keyKeeper.isActivated(key) || keyKeeper.isActivated(key + type)));
//            }
                HashMap<String, String> param = new HashMap<>();
                param.put("type", "version");
                param.put("version", version);
                if (version.contains("J")) {
                    param.put("language", "java");
                } else if (version.contains("C")) {
                    param.put("language", "c");
                } else {
                    param.put("language", "unknow");
                }
                param.put("testKey", "");
                param.put("onlineKey", key.substring(0, 32));
                String[] urls = getParamAsStrings(RuntimeEnv.META_KEYINFO_HOSTS);
                HttpUtils.Result resultPost = HttpUtils.httpsPost(urls[0] + "api_get_version", param);
                response.getWriter().append(hostKeeper.getOnlineHostLines()).flush();
            } else if (keyKeeper.isTest(key)) {
                //			if (!keyKeeper.isActivated(key)) {
                //				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                //						"key not activated for test data load.");
                //				return;
                //			}
                //get version
                logger.info(key + " is test");
                HashMap<String, String> param = new HashMap<>();
                param.put("type", "version");
                param.put("version", version);
                if (version.contains("J")) {
                    param.put("language", "java");
                } else if (version.contains("C")) {
                    param.put("language", "c");
                } else {
                    param.put("language", "unknow");
                }
                param.put("testKey", key.substring(0, 32));
                param.put("onlineKey", "");
                String[] urls = getParamAsStrings(RuntimeEnv.META_KEYINFO_HOSTS);
                HttpUtils.Result resultPost = HttpUtils.httpsPost(urls[0] + "api_get_version", param);
                response.getWriter().append(hostKeeper.getTestHostLines()).flush();
            } else {
                logger.info(key + "key not valid");
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "key not valid.");
                return;
            }
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            logger.error(e, e);
        }
    }

}
